<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="770px"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <div class="tab-wrap d-flex justify-content-between cursor-pointer">
      <div
        v-for="(item, index) in tabs"
        :key="index"
        :class="{
          tab_item_one: item.value === 'one',
          tab_item_two: item.value === 'two',
          tab_item_three: item.value === 'three',
          tab_item_active__is: item.id <= tabIndex
        }"
      >
        <i class="el-icon-success size-16"></i>
        {{ item.label }}
      </div>
    </div>
    <div v-if="tabIndex == 1" class="step-section">
      <div class="sections">
        <div class="sections__title">
          模板名称
        </div>
        <div class="content">
          <flexbox class="file-select">
            <el-input
              v-model="templateForm.templateName"
              placeholder="请输入模板名称"
            />
          </flexbox>
        </div>
      </div>
      <div class="sections">
        <div class="sections__title">模板上传</div>
        <div class="content">
          <flexbox class="file-select">
            <el-input :disabled="true" :placeholder="fileForm.name" />
            <el-button type="primary" @click="selectFile">选择文件</el-button>
            <input
              id="importInputFile"
              type="file"
              accept=".doc,.docx,.pdf"
              @change="uploadFile"
            />
          </flexbox>
          <div class="step-section__tips">
            文件格式：.doc、.docx、.pdf；文件大小：不大于10M
          </div>
        </div>
      </div>
    </div>

    <div v-if="tabIndex == 2" class="step-section">
      <div class="sections">
        <div class="sections__title">签署方1:</div>
        <div class="content">
          <flexbox class="file-select">
            <el-input :disabled="true" placeholder="固定为学员签署" />
          </flexbox>
        </div>
      </div>
      <div class="sections" v-for="(item, index) in inpList" :key="item.id">
        <div class="sections__title">{{ item.signerKey }}:</div>
        <div class="content">
          <flexbox class="file-select select-item">
            <el-select
              v-model="item.subjectId"
              placeholder="请选择"
              style="width: 100%;"
              @change="signerChange(index)"
            >
              <el-option
                v-for="(item, index) in allSignatureList"
                :key="index"
                :label="item.enterpriseName"
                :value="item.subjectId"
              />
            </el-select>
            <i
              class="el-icon-remove delete-btn"
              v-if="item.id != 1 && item.id === inpList.length"
              @click="deleteHandle"
            ></i>
          </flexbox>
        </div>
      </div>
      <div
        class="add-btn cursor-pointer"
        v-if="addNameVisible"
        @click="addHandle"
      >
        <i class="el-icon-plus"></i>
        添加签署名称
      </div>
    </div>

    <div v-if="tabIndex == 3" class="step-section">
      <div
        class="sections three-sections"
        v-for="item in systemList"
        :key="item.id"
      >
        <div class="sections__title">{{ `字段名称${item.id}:` }}</div>
        <div class="content">
          <flexbox class="file-select select-item">
            <el-input v-model="item.paramsKey" placeholder="请输入字段名称" />
            <i
              class="el-icon-remove delete-btn"
              v-if="item.id != 1 && item.id === systemList.length"
              @click="deleteSystemHandle"
            ></i>
          </flexbox>
        </div>
        <div class="sections__title">字段类型:</div>
        <div class="content">
          <flexbox class="file-select select-item">
            <el-select
              v-model="item.paramsType"
              placeholder="请选择"
              style="width: 100%;"
            >
              <el-option
                v-for="(item, index) in [
                  { name: '单行文本', value: 1 },
                  { name: '日期', value: 5 },
                  { name: '多行文本', value: 8 }
                ]"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </flexbox>
        </div>
      </div>
      <div
        class="add-btn cursor-pointer"
        v-if="addSystemVisible"
        @click="addSystemHandle"
      >
        <i class="el-icon-plus"></i>
        添加配置字段
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="tabClick('down')" v-if="tabIndex != 1"
        >返回上一步</el-button
      >
      <el-button type="primary" @click="tabClick('up')">{{
        tabIndex == 3 ? "确认完成" : "确认下一步"
      }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";

import {
  addTemplate,
  updateTemplate,
  queryAllSignatureList
} from "@/api/admin/agreement";

import { guid } from "@/utils";
export default {
  data() {
    return {
      dialogVisible: false,
      addNameVisible: true, // 配置签署方添加
      addSystemVisible: true, // 配置字段添加
      tabIndex: 1,
      fileId: null, // 文件id
      fileForm: {
        name: "请选择文件上传"
      },
      templateForm: {
        // 新增模板
        templateName: "", // 模板名称
        templateId: "", // 模板ID
        templateNo: "", // 模板编号
        paramsList: [], // 字段列表
        signerList: [] // 签署方列表
      },
      tabs: [
        {
          id: 1,
          label: "上传协议模板",
          value: "one"
        },
        {
          id: 2,
          label: "配置签署方",
          value: "two"
        },
        {
          id: 3,
          label: "配置填写字段",
          value: "three"
        }
      ],
      inpList: [
        {
          enterpriseName: "",
          subjectId: null,
          signerKey: '签署方2',
          id: 1
        }
      ], // 签署方列表

      // 全量签署方
      allSignatureList: [],
      systemList: [{ paramsKey: "", paramsType: "", id: 1 }] // 配置字段列表
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    title() {
      const data = this.action.data;
      // 有回显的值
      if (data && this.action.type === "update" && Object.keys(data).length) {
        this.fileId = data.fileId;
        this.fileForm.name = data.fileName;
        this.templateForm.templateName = data.model.templateName;
        this.templateForm.templateId = data.model.templateId;
        this.templateForm.templateNo = data.model.templateNo;
        this.inpList = data.model.signerList.map((item, index) => {
          return {
            signerKey: item.signerKey,
            enterpriseName: item.enterpriseName,
            subjectId: item.subjectId
          };
        });
        this.systemList = data.model.paramsList.map((item, index) => {
          return {
            paramsKey: item.paramsKey,
            paramsType: item.paramsType,
            id: index + 1
          };
        });
      }
      return this.action.type === "update" ? "编辑协议模版" : "新增协议模版";
    }
  },
  props: {
    show: Boolean,
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {}
        };
      }
    }
  },
  mounted() {
    this.show ? (this.dialogVisible = true) : (this.dialogVisible = false);
    // 获取全量签章主体
    queryAllSignatureList().then(res => {
      this.allSignatureList = res.data;
    });
  },
  methods: {
    tabClick(type) {
      if (this.tabIndex != 3 || type === "down") {
        if (type === "down") {
          // 返回 返回不校验数据是否完整
          this.tabIndex--;
        } else if (type === "up") {
          // 下一步 校验数据是否完整
          if (
            this.tabIndex == 1 &&
            !(this.fileId && this.templateForm.templateName)
          ) {
            this.$message.error("请将数据填写完整");
            return;
          } else if (this.tabIndex == 2) {
            let temp = false;
            this.inpList.forEach(item => {
              if (!item.enterpriseName) {
                temp = true;
              }
            });
            if (temp) {
              this.$message.error("请将数据填写完整");
              return;
            }
          }
          this.tabIndex++;
        }
      } else if (this.tabIndex === 3 && type === "up") {
        let temp = false;
        this.systemList.forEach(item => {
          if (!item.paramsKey || !item.paramsType) {
            temp = true;
          }
        });
        if (temp) {
          this.$message.error("请将数据填写完整");
          return;
        }
        this.templateForm.paramsList = this.systemList.map(item => {
          return {
            paramsKey: item.paramsKey,
            paramsType: item.paramsType
          };
        });
        this.templateForm.signerList = this.inpList.map(item => {
          return {
            enterpriseName: item.enterpriseName,
            signerKey: item.signerKey,
            subjectId: item.subjectId
          };
        });
        // 提交
        this.submitTemp();
      }
    },

    // 保存模板
    submitTemp() {
      if (this.action.type == "update") {
      }
      let request =
        this.action.type === "update" ? updateTemplate : addTemplate;
      request(this.templateForm, {
        fileId: this.fileId
      })
        .then(res => {
          setTimeout(() => {
            window.open(res.data.result, "_blank");
          }, 1500);
          this.$message.success(
            this.action.type == "update" ? "编辑完成，跳转到爱签页面配置" : "添加完成，跳转到爱签页面配置"
          );
          this.handleClose();
          // 保存成功
          this.$emit("save-success", {
            type: "signature"
          });
        })
        .catch(() => {});
    },

    // 增加签署方
    addHandle() {
      const len = this.inpList.length;
      this.inpList.push({
        enterpriseName: "",
        subjectId: null,
        signerKey: `签署方${len + 1 + 1}`,
        id: len + 1
      });

      if (this.inpList.length >= 4) {
        this.addNameVisible = false;
      }
    },

    // 协议方更改
    signerChange(index) {
      const val = this.inpList[index].subjectId;
      this.allSignatureList.forEach(item => {
        if (item.subjectId == val) {
          this.inpList[index] = {
            ...this.inpList[index],
            enterpriseName: item.enterpriseName,
            signerKey: this.inpList[index].signerKey
          };
        }
      });
    },

    // 增加配置字段
    addSystemHandle() {
      const len = this.systemList.length;
      this.systemList.push({
        paramsKey: "",
        paramsType: "",
        id: len + 1
      });
      if (this.systemList.length > 5) {
        this.addSystemVisible = false;
      }
    },

    // 删除签署名称
    deleteHandle() {
      this.inpList.splice(this.inpList.length - 1, 1);
      this.addNameVisible = true;
    },

    // 删除配置字段
    deleteSystemHandle() {
      this.systemList.splice(this.systemList.length - 1, 1);
      this.addSystemVisible = true;
    },

    handleClose() {
      this.$emit("close");
      this.dialogVisible = false;
    },

    // 选择文件
    selectFile() {
      document.getElementById("importInputFile").click();
    },

    /** 图片选择出发 */
    uploadFile(event) {
      var files = event.target.files;
      const file = files[0];
      const fileMaxSize = 1024 * 1024 * 10;
      if (file.size > fileMaxSize) {
        this.$message.error("文档大小不超过10M！");
        return;
      }
      this.fileForm.name = file.name;
      this.$wkUploadFile
        .upload({
          file: file,
          params: {
            batchId: guid()
          }
        })
        .then(res => {
          console.log(res);
          this.fileId = res.res.data.fileId;
        })
        .catch(() => {});
      event.target.value = "";
    }
  }
};
</script>

<style lang="scss" scoped>
.tab-wrap {
  width: 722px;
  margin-bottom: 30px;
  .tab_item_one {
    width: 238px;
    height: 40px;
    color: #fff;
    text-align: center;
    line-height: 40px;
    background-color: #eaf3ff;
    position: relative;
    border-top-left-radius: 20px;
    border-bottom-left-radius: 20px;
  }
  .tab_item_one::after {
    content: " ";
    display: block;
    position: absolute;
    right: -30px;
    top: 0;
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-right: 10px solid transparent;
    border-left: 20px solid #0066f9;
    border-bottom: 20px solid transparent;
    z-index: 1;
  }
  .tab_item_two {
    width: 238px;
    height: 40px;
    color: #7ab3ff;
    text-align: center;
    line-height: 40px;
    background-color: #eaf3ff;
    position: relative;
  }
  .tab_item_two::before {
    content: " ";
    display: block;
    position: absolute;
    left: 0px;
    top: 0;
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-right: 10px solid transparent;
    border-left: 20px solid #fff;
    border-bottom: 20px solid transparent;
  }
  .tab_item_two::after {
    content: " ";
    display: block;
    position: absolute;
    right: -30px;
    top: 0;
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-right: 10px solid transparent;
    border-left: 20px solid #eaf3ff;
    border-bottom: 20px solid transparent;
    z-index: 1;
  }
  .tab_item_three {
    width: 238px;
    height: 40px;
    color: #7ab3ff;
    text-align: center;
    line-height: 40px;
    background-color: #eaf3ff;
    position: relative;
    border-top-right-radius: 20px;
    border-bottom-right-radius: 20px;
  }
  .tab_item_three::before {
    content: " ";
    display: block;
    position: absolute;
    left: 0px;
    top: 0;
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-right: 10px solid transparent;
    border-left: 20px solid #fff;
    border-bottom: 20px solid transparent;
  }

  .tab_item_active__is {
    background-color: #0066f9;
    color: #fff;
  }
  .tab_item_active__is::after {
    border-left: 20px solid #0066f9;
  }
}

.step-section {
  min-height: 300px;
  position: relative;
  margin-bottom: 24px;
  /deep/ .el-loading-spinner {
    top: 45%;
    .el-icon-loading {
      font-size: 40px;
      color: #999;
    }

    .el-loading-text {
      color: #333;
      margin: 8px 0;
    }
  }

  &__tips {
    margin-top: 16px;
    height: 26px;
    background: #e0eaff;
    font-size: 12px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #333333;
    line-height: 26px;
    padding: 0 10px;
  }
}

.sections {
  font-size: 14px;
  color: #333;
  margin-top: 20px;

  &__title {
    color: #666;
    font-weight: 600;
  }

  &__tips {
    padding-left: 30px;
    margin: 8px 0 15px;
    color: #999;
    font-size: 12px;
    line-height: 1.4;
  }

  .download {
    cursor: pointer;
    color: #2362fb;
  }

  .delete-btn {
    position: absolute;
    right: -20px;
  }

  .select-item {
    margin-top: 24px;
  }
  .select-item:first-child {
    margin: 0;
  }
}
.add-btn {
  margin: 16px 0;
  height: 32px;
  line-height: 32px;
  border: 1px dashed #0068f7;
  color: #0066f9;
  border-radius: 4px;
  text-align: center;
}
.three-sections {
  .content {
    padding-bottom: 15px;
  }
  .content:last-child {
    border-bottom: 1px solid #e5e5e5;
  }
}

.content {
  padding: 10px 0px 0px 0px;
  .el-select {
    width: 400px;
  }
  .user-cell {
    width: 400px;
  }
}
#importInputFile {
  display: none;
}

/deep/ .el-dialog__body {
  padding: 0 25px 0px 25px;
}
</style>
